#include "StdAfx.h"
#include "BlastPileDBManager.h"
#include "MatchingOreAddIn.h"

CRegionManager::CRegionManager(CdmDB* pRegionDB)
	: m_pRegionDB(pRegionDB)
	, m_iRowCount(0)
	, m_iColCount(0)
{
}

CRegionManager::~CRegionManager(void)
{
}

bool CRegionManager::GetBlkEntArr(CEntityArray& blkEntArr, bool bSort /* = true */, bool bFirstI_SecondeJ /* = true */)
{
	if (NULL == m_pRegionDB)
		return false;

	CDataTable* pTable = m_pRegionDB->GetDataTable();
	if (NULL == pTable)
		return false;

	blkEntArr.Empty();

	if (bSort)
	{
		int iFirstIndex = -1;
		int iSecondIndex = -1;
		if (bFirstI_SecondeJ)
		{
			iFirstIndex = pTable->Get_Field_Id(REGION_LATERAL_AXIS_INDEX_FLD);
			iSecondIndex = pTable->Get_Field_Id(REGION_VERTICAL_AXIS_INDEX_FLD);
		}
		else
		{
			iFirstIndex = pTable->Get_Field_Id(REGION_VERTICAL_AXIS_INDEX_FLD);
			iSecondIndex = pTable->Get_Field_Id(REGION_LATERAL_AXIS_INDEX_FLD);
		}
		pTable->Set_Index(iFirstIndex, iSecondIndex);
	}

	int iRecNum = pTable->Get_Record_Count();
	for (int i=0; i<iRecNum; ++i)
	{
		CDataTableRecord* pRecord = pTable->Get_Record_byIndex(i);
		CAttRecord* pAttRec = (CAttRecord*)pRecord;
		void* pUser = pRecord->GetUserData();
		CdmEntity* pEntity = (CdmEntity*)pUser;

		if (pEntity->IsDeleted() || pEntity->GetType() != ETT_POLYLINE || pEntity->GetEntityType() != REGION_MAKER)
		{
			continue;
		}
		blkEntArr.Append(pEntity);
	}///:~for--i	

	GetRowColData(pTable);

	return true;
}

bool CRegionManager::GetRowColData(CDataTable* pTable, bool bFirstI_SecondeJ/* = true*/)
{
	if (NULL == pTable)
		return false;

	char* pRowFld = NULL;
	char* pColFld = NULL;
	bool m_bIJCoding = true;
	if (bFirstI_SecondeJ)
	{
		pRowFld = REGION_VERTICAL_AXIS_INDEX_FLD;
		pColFld = REGION_LATERAL_AXIS_INDEX_FLD;
	}
	else
	{
		pRowFld = REGION_LATERAL_AXIS_INDEX_FLD;
		pColFld = REGION_VERTICAL_AXIS_INDEX_FLD;
	}

	std::set<int> set_iColIndex;
	bool bFilter = FilterFld(set_iColIndex, pTable, pRowFld);
	if (bFilter && !set_iColIndex.empty())
	{
		m_iColCount = (int)set_iColIndex.size();
	}
	std::set<int> set_iRowIndex;
	bFilter = FilterFld(set_iRowIndex, pTable, pColFld);
	if (bFilter && !set_iRowIndex.empty())
	{
		m_iRowCount = (int)set_iRowIndex.size();
	}

	return true;
}

bool CRegionManager::FilterFld(std::set<int>& siIndexID, CDataTable* pTable, const char* pFld)
{
	if (NULL == pTable || NULL == pFld)
		return false;

	int iFldID = pTable->Get_Field_Id(pFld);
	if (-1 == iFldID)
		return false;

	siIndexID.clear();
	int iRecNum = pTable->Get_Record_Count();
	for (int i=0; i<iRecNum; ++i)
	{
		CDataTableRecord* pRecord = pTable->Get_Record(i);
		siIndexID.insert(pRecord->asInt(pFld));
	}///:~for

	return true;
}
